import { login } from "./../api/api"
const INCREMENT = 'INCREMENT'
const DECREMENT = 'DECREMENT'
const LOGINSTATE = 'LOGINSTATE'
const MODIFY_USER_INFO = 'MODIFY_USER_INFO'
// action 函数，调用后返回一个Action对象；
export const addCount = (num) => {
  return { 'type': INCREMENT, num }
}

export const decrementCount = (num) => {
  return { 'type': DECREMENT, num }
}

export const modifyLoginState = (boolValue) => {
  return { 'type': LOGINSTATE, boolValue }
}

export const modifyUserInfo = (info, boolValue) => {
  return { 'type': MODIFY_USER_INFO, info, boolValue }
}

// 异步的action函数
export const userLogin = (params) => {
  // 控制反转： 把返回的函数，再继续调用
  return async function (dispatch) {
    return login(params)
      .then(res => {
        if (res.code === 0) {
          return dispatch(modifyUserInfo(res.data, true))
        } else {
          return dispatch(modifyUserInfo(res.data, false))
        }
      })
      .catch(err => {
        throw new Error(err)
      })
  }
}

export const modifyUser = (params) => {
  return async (dispath) => {
    return fetch("http://127.0.0.1:80/user/modifyUserInfo", {
      method: 'post',
      headers: { "content-type": "application/json" }, //要写它，不然后台拿不到参数
      body: JSON.stringify(params)  // 参数
    })
      .then(res => res.json())
      .then(resData => {
        if (resData.code === 0) {

          return dispath(modifyUserInfo(params, true))
        } else {
          // throw new Error(res.msg)
          return dispath(modifyUserInfo({}))
        }
      })
  }

}